<template>
  <div
    class="platform-frame"
    v-ns-class>
    <frame-header
      class="platform-frame-header"
      v-ns-class />
    <div
      class="platform-frame-body"
      v-ns-class>
      <frame-sidebar
        class="platform-frame-sidebar"
        v-ns-class
        @clickMenu="clickMenu" />
      <div
        class="platform-frame-main"
        v-ns-class
        v-loading="loadingApp">
        <div
          class="platform-frame-view"
          v-ns-class
          ref="viewRef"></div>
        <!--
        <p @click="() => (cls = !cls)">这是框架层容器内默认的元素，当加载微应用时会被替换成微应用内容</p>
        -->
      </div>
    </div>
    <footer
      class="platform-frame-footer"
      v-ns-class></footer>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, onUnmounted, ref } from 'vue'
import { useQiankun } from '@/service/qiankun.service'
import FrameSidebar from './frame-sidebar/frame-sidebar.vue'
import FrameHeader from './frame-header/frame-header.vue'
import { apps, Menu, MenuType, useIframeRouter } from './frame.service'

export default defineComponent({
  name: 'pl-frame',
  components: {
    FrameSidebar,
    FrameHeader,
  },
  setup() {
    const qk = useQiankun()
    const viewRef = ref<HTMLDivElement>()
    const iframeRouter = useIframeRouter()
    const loadingApp = computed(() => qk.loadingApp.value || iframeRouter.loading.value)
    const clickMenu = (menu: Menu, parent: Menu) => {
      if (menu.type === MenuType.MICRO) {
        qk.goRouter(menu.url as string)
      } else if (menu.type === MenuType.IFRAME) {
        iframeRouter.goRouter(viewRef.value as HTMLDivElement, menu)
      }
    }

    qk.qiankunFrame.setState({
      userInfo: {
        id: '1',
        name: '管理员',
        age: 20,
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
      },
    })

    onMounted(() => {
      qk.registryApps(apps, viewRef.value as HTMLDivElement)

      qk.start({
        sandbox: {
          loose: true,
        },
      })
    })

    onUnmounted(() => {
      qk.destroy()
    })

    return {
      clickMenu,
      viewRef,
      loadingApp,
    }
  },
})
</script>
